<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


class UserModel extends Model
{


	//通过用户ID取得用户信息
	function getUserByID($userID)
	{
		$map = array('user_id' => $userID);
		return $this->where($map)->find();
	}


	//通过邮箱取得用户信息
	function getUserByEmail($email)
	{
		$map = array('email' => $email);
		return $this->where($map)->find();
	}


	//通过用户名取得用户信息
	function getUserByName($username)
	{
	    $map = array('username' => $username);
		return $this->where($map)->find();
	}
	
	
	//记录用户登录cookie
	function cookieUser($userID)
	{
        $user = $this->find($userID);
    	$userCookie = array(
			'user_id' => $user['user_id'],
			'auth'    => kg_auth_code($user['user_id'] ."\t". $user['username'], 'encode'),
		);
		cookie('user', $userCookie, 30 * 86400);
    }
	
	
	//奖励邀请人
	function rewardInviter($userID)
	{
    	$points = get_activity_points('invite');
		$this->updatePointCount($userID, $points);
    	$this->logActivity($userID, 'invite', $points);
	}

	
	//更新积分
	function updatePointCount($userID, $points)
	{
		if ($points > 0)
		{
			$this->setInc('point_count', 'user_id='.$userID, abs($points));
		}
		else
		{
			$this->setDec('point_count', 'user_id='.$userID, abs($points));
		}
		$this->autoUpgradeLevel($userID);
	}


	//自动升级
	function autoUpgradeLevel($userID)
	{
		$user = $this->find($userID);
		$userGroup = identify_group_by_points($user['point_count']);
		if (!empty($user) && $userGroup != $user['user_group'] && !in_array($user['user_group'], array(1,2,3,4,5,6,8)))
		{
			$this->where('user_id='.$userID)->setField('user_group', $userGroup);
		}
	}
	

	//记录活动
	function logActivity($userID, $type, $point=0, $related=0)
	{
		$Model = M('Activity');
		$data  = array(
			'user_id'     => intval($userID),
			'type'        => $type,
			'point'       => intval($point),
			'related_id'  => intval($related),
			'create_time' => time(),
		);
		$Model->add($data);
	}


	//登录检查
	function checkLogin() {
		$Model  = M('FailedLogin');
		$map    = array('client_ip' => get_client_ip());
		$result = $Model->where($map)->find();
		if($result)
		{
			if(time() - $result['create_time'] > 1800)
			{
				return 3;
			}
			elseif ($result['failed_count'] < get_site_config('max_login_attempts'))
			{
				return 2;
			}
			else
			{
				return 0;
			}
		}
		else
		{
			return 1;
		}
	}


	//记录失败登录
	function logFailedLogin($perms)
	{
		$Model  = M('FailedLogin');
		$clientIP = get_client_ip();
		switch($perms)
		{
			case 1:
				$data = array(
					'client_ip'    => $clientIP,
					'failed_count' => 1,
					'create_time'  => time(),
				);
				$Model->replace($data);
				break;
			case 2:
				$map  = array('client_ip' => $clientIP);
				$data = array(
					'failed_count' => array('exp', 'failed_count+1'),
					'create_time'  => time(),
				);
				$Model->where($map)->save($data);
				break;
			case 3:
				$map  = array('client_ip' => $clientIP);
				$data = array(
					'failed_count' => 1,
					'create_time'  => time(),
				);
				$Model->where($map)->save($data);
				$map = array('create_time' => array('lt', time() - 1800));
				$Model->where($map)->delete();
				break;
		}
	}


	//A用户是否有查看B用户分享的权限
	function getShareSettings($uidA, $uidB)
	{
	    $Follow = M('UserFollow');

		$userB = $this->find($uidB);

		//用户隐私设置
		$perms = array(
			'share_qa_activity' => 0,
			'share_network_activity' => 0,
		);

		$map = array(
			'source_user' => $uidA,
			'target_user' => $uidB,
			'status' => 1,
		);
		$following = $Follow->where($map)->count();//A关注B(A是B的粉丝)

		$map = array(
			'source_user' => $uidB,
			'target_user' => $uidA,
			'status' => 1,
		);
		$followed = $Follow->where($map)->count(); //A被B关注(B是A的粉丝)

		//隐私设置(0=>所有人,1=>关注以及粉丝,2=>关注)
		switch ($userB['qa_activity'])
		{
			case 0:
				$perms['share_qa_activity'] = 1;
				break;
			case 1:
				$perms['share_qa_activity'] = $following>0 || $followed>0;
				break;
			case 2:
				$perms['share_qa_activity'] = $following;
				break;
		}
		switch ($userB['network_activity'])
		{
			case 0:
				$perms['share_network_activity'] = 1;
				break;
			case 1:
				$perms['share_network_activity'] = $following>0 || $followed>0;
				break;
			case 2:
				$perms['share_network_activity'] = $following;
				break;
		}
		if ($uidA == $uidB)
		{
			$perms['share_qa_activity'] = 1;
			$perms['share_network_activity'] = 1;
		}
		return $perms;
	}

	
	/**
	 * 通过用户ID删除用户
	 *
	 * @param array $userID
	 */
	function deleteUserByID($userID)
	{
	    $prefix = $this->tablePrefix;
	    $userIDs = implode(',', $userID);

	    $Question = M('Question');
	    $Answer   = M('Answer');
	    $Comment  = M('Comment');
	    $Activity = M('Activity');
	    $StarredQuestion  = M('StarredQuestion');
	    $FollowedQuestion = M('FollowedQuestion');
	    $QuestionTag = M('QuestionTag');
	    $UserFollow  = M('UserFollow');
	    $UserAccount = M('UserAccount');
	    $Invitation  = M('Invitation');

	    //删除其他用户的相关星号标记
	    $sql = "DELETE FROM {$prefix}starred_question WHERE question_id IN (SELECT question_id FROM {$prefix}question WHERE poster_id IN({$userIDs}))";
	    $StarredQuestion->query($sql);

	    //删除用户星号标记
	    $map = array('user_id' => array('in', $userID));
	    $StarredQuestion->where($map)->delete();

	    //删除其他用户的相关问题关注
	    $sql = "DELETE FROM {$prefix}followed_question WHERE question_id IN (SELECT question_id FROM {$prefix}question WHERE poster_id IN({$userIDs}))";
	    $FollowedQuestion->query($sql);

	    //删除用户关注问题
	    $map = array('user_id' => array('in', $userID));
	    $FollowedQuestion->where($map)->delete();

	    //删除问题标签
	    $sql = "DELETE FROM {$prefix}question_tag WHERE question_id IN (SELECT question_id FROM {$prefix}question WHERE poster_id IN({$userIDs}))";
	    $QuestionTag->query($sql);

	    //删除activity记录
	    $map = array('user_id' => array('in', $userID));
	    $Activity->where($map)->delete();

	    //删除用户关注关系
	    $map = array(
	       'source_user' => array('in', $userID),
	       'target_user' => array('in', $userID),
	       '_logic' => 'or',
	    );
	    $UserFollow->where($map)->delete();

        //删除评论
	    $map = array('poster_id' => array('in', $userID));
	    $Comment->where($map)->delete();

	    //删除答案
	    $map = array('poster_id' => array('in', $userID));
	    $Answer->where($map)->delete();

	    //删除问题
	    $map = array('poster_id' => array('in', $userID));
		$Question->where($map)->delete();
		
		//删除邀请码
		$map = array('user_id' => array('in', $userID));
		$Invitation->where($map)->delete();

		//删除关联帐号
		$map = array('user_id' => array('in', $userID));
		$UserAccount->where($map)->delete();

		//删除主帐号
		$map = array('user_id' => array('in', $userID));
		$this->where($map)->delete();
	}

}

/* End of file UserModel.class.php */
/* Location: ./App/Lib/Model/UserModel.class.php */